from pydub import AudioSegment

def mix_audio(main_audio_path, background_audio_path, output_path, background_volume_reduction=10):
    """
    Mix a main audio file with a background audio file, adjusting the background volume.
    
    Args:
        main_audio_path (str): Path to the main audio file
        background_audio_path (str): Path to the background audio file
        output_path (str): Path where the mixed audio will be saved
        background_volume_reduction (int): How many decibels to reduce the background volume by
    """
    # Load the audio files
    print(f"Loading main audio: {main_audio_path}")
    main_audio = AudioSegment.from_mp3(main_audio_path)
    
    print(f"Loading background audio: {background_audio_path}")
    background_audio = AudioSegment.from_mp3(background_audio_path)
    
    # Adjust the background volume (reduce it by the specified amount)
    background_audio = background_audio - background_volume_reduction
    
    # Make sure background is at least as long as the main audio
    if len(background_audio) < len(main_audio):
        # Loop the background audio until it's long enough
        background_audio = background_audio * (len(main_audio) // len(background_audio) + 1)
    
    # Trim the background audio to match the length of the main audio
    background_audio = background_audio[:len(main_audio)]
    
    # Overlay (mix) the two audio files
    print("Mixing audio files...")
    mixed_audio = main_audio.overlay(background_audio)
    
    # Export the result
    print(f"Exporting mixed audio to: {output_path}")
    mixed_audio.export(output_path, format="mp3")
    print("Done!")

if __name__ == "__main__":
    # File paths
    main_audio = "sound.mp3"
    background_audio = "backsound.mp3"
    output_file = "mixed_output.mp3"
    
    # You can adjust this value to make the background music louder (lower value)
    # or quieter (higher value)
    background_volume_reduction = 10  # in decibels
    
    mix_audio(main_audio, background_audio, output_file, background_volume_reduction)
    print(f"Successfully mixed audio files! Output saved to {output_file}")
